import axios from "axios";
// import { ElLoading } from "element-plus";
import type { AxiosRequestConfig, AxiosInstance } from "axios";
import type { RequestInterceptors, RequestConfig } from "./type";

class Request {
  instance: AxiosInstance;
  // 拦截器：可选
  interceptors?: RequestInterceptors;
  loading: any;

  constructor(config: RequestConfig) {
    this.instance = axios.create(config);

    this.interceptors = config.interceptors;

    /* 实例单独传递的拦截器 */
    // 请求拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    );
    // 响应拦截器
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    );

    /* 全局拦截器 */
    this.instance.interceptors.request.use(
      (config) => {
        /* this.loading = ElLoading.service({
          lock: true,
          background: "rgba(0,0,0,0.5)",
          text: "数据加载中..."
        }); */
        return config;
      },
      (err) => {
        return err;
      }
    );
    this.instance.interceptors.response.use(
      (res) => {
        // this.loading.close();
        return res.data;
      },
      (err) => {
        return err;
      }
    );
  }
  /* request(config: AxiosRequestConfig): void {
    this.instance.request(config).then((res) => {
      console.log(res);
    });
  } */
  request<T = any>(config: AxiosRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      this.instance
        .request<any, T>(config)
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
  get<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: "get" });
  }
  post<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: "post" });
  }
  delete<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: "delete" });
  }
  patch<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: "patch" });
  }
}

export default Request;
